"use strict";
const moment = require("moment");
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Role extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      models.Role.belongsToMany(models.User, {
        through: models.UsersRoles,
        foreignKey: "roleId",
        as: "users",
      });
      models.Role.belongsToMany(models.Menu, {
        through: models.RolesMenus,
        foreignKey: "roleId",
        as: "menus",
      });
    }
  }
  Role.init(
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: "角色名必须填写。" },
          notEmpty: { msg: "角色名不能为空。" },
          len: { args: [1, 20], msg: "角色名长度必须是1 ~ 20之间。" },
        },
      },
      code: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: "角色编码必须填写。" },
          notEmpty: { msg: "角色编码不能为空。" },
          len: { args: [1, 45], msg: "角色编码长度必须是1 ~ 45之间。" },
          async isUnique(value) {
            const role = await Role.findOne({ where: { code: value } });
            if (role) {
              throw new Error("角色编码已经存在。");
            }
          },
        },
      },
      remark: DataTypes.TEXT,
      status: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        validate: {
          notNull: { msg: "状态必须填写。" },
          notEmpty: { msg: "状态不能为空。" },
        },
      },
      createdAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue("createdAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
      updatedAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue("updatedAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
    },
    {
      sequelize,
      modelName: "Role",
    }
  );
  return Role;
};
